package com.ai.service.security.impl;

import com.ai.common.CommonResponse;
import com.ai.entity.security.SysPermission;
import com.ai.entity.security.SysRolePermissionRelation;
import com.ai.mapper.security.SysPermissionMapper;
import com.ai.model.param.SysPermissionParam;
import com.ai.service.security.ISysPermissionService;
import com.ai.service.security.ISysRolePermissionRelationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2023-04-04 19:46:06
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {


    @Resource
    private ISysRolePermissionRelationService iSysRolePermissionRelationService;


    /**
     * 查询用户的权限列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysPermission> selectListByUser(Integer userId) {
        return baseMapper.selectListByUser(userId);
    }

    /**
     * 查询具体某个接口的权限
     *
     * @param path
     * @return
     */
    @Override
    public List<SysPermission> selectListByPath(String path) {
        return baseMapper.selectListByPath(path);
    }

    /**
     * 新增权限类型
     * @param permissionParam
     * @return
     */
    @Override
    public CommonResponse<String> add(SysPermissionParam permissionParam) {

        List<SysPermission> permissionList = this.list();
//        判断权限code
        List<String> permissionCodeList =
                permissionList.stream().map(SysPermission::getPermissionCode).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(permissionCodeList) && permissionCodeList.contains(permissionParam.getPermissionCode())){
            return CommonResponse.error("权限code已存在，请勿重复添加");
        }
//        判断权限name
        List<String> permissionNameList =
                permissionList.stream().map(SysPermission::getPermissionName).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(permissionNameList)&& permissionNameList.contains(permissionParam.getPermissionName())){
            return CommonResponse.error("权限名已存在，请勿重复添加");
        }

        SysPermission sysPermission = new SysPermission();
        sysPermission.setPermissionCode(permissionParam.getPermissionCode());
        sysPermission.setPermissionName(permissionParam.getPermissionName());
        boolean save = this.save(sysPermission);
        if (save){
            return CommonResponse.ok("新增成功");
        }else {
            return CommonResponse.error("新增失败");
        }
    }

    /**
     * 更新权限信息
     * @param permissionParam
     * @return
     */
    @Override
    public CommonResponse<String> updatePermission(SysPermissionParam permissionParam) {

        List<SysPermission> permissionList = this.list();
//        判断权限code
        List<String> permissionCodeList =
                permissionList.stream().filter(sysPermission -> {
                    return (!(permissionParam.getPermissionName().equals(sysPermission.getPermissionName())));
                }).map(SysPermission::getPermissionCode).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(permissionCodeList) && permissionCodeList.contains(permissionParam.getPermissionCode())){
            return CommonResponse.error("权限code已存在，请勿重复添加");
        }
//        判断权限name
        List<String> permissionNameList =
                permissionList.stream().filter(sysPermission -> {
                    return (!(permissionParam.getPermissionName().equals(sysPermission.getPermissionName())));
                }).map(SysPermission::getPermissionName).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(permissionNameList)&& permissionNameList.contains(permissionParam.getPermissionName())){
            return CommonResponse.error("权限名已存在，请勿重复添加");
        }
        SysPermission sysPermission = new SysPermission();
        sysPermission.setId(Integer.valueOf(permissionParam.getId()));
        sysPermission.setPermissionCode(permissionParam.getPermissionCode());
        sysPermission.setPermissionName(permissionParam.getPermissionName());
        boolean b = this.updateById(sysPermission);
        if (b){
            return CommonResponse.ok("更新成功");
        }else {
            return CommonResponse.error("更新失败");
        }

    }

    @Override
    public CommonResponse permissionList(String roleId) {
        HashMap<String, Object> result = new HashMap<>();
        ArrayList<SysPermission> checked = new ArrayList<>();
        ArrayList<SysPermission> unChecked = new ArrayList<>();

        //获取所有权限列表
        List<SysPermission> allPermissionList = this.list();
        //获取当前用户所拥有的权限
        List<SysRolePermissionRelation> rolePermissionRelations = iSysRolePermissionRelationService.list(new QueryWrapper<SysRolePermissionRelation>()
                .eq("role_id", roleId));

        if (CollectionUtils.isEmpty(rolePermissionRelations)){
            //如果当前用户没有任何权限
            unChecked.addAll(allPermissionList);
        }else {
            //当前用户已经拥有部分权限，遍历剔除
            List<Integer> collectPermission = rolePermissionRelations.stream().map(SysRolePermissionRelation::getPermissionId)
                    .collect(Collectors.toList());
            for (SysPermission sysPermission : allPermissionList) {
                //如果包含当前权限
                if (collectPermission.contains(sysPermission.getId())){
                    checked.add(sysPermission);
                }else {
                    unChecked.add(sysPermission);
                }
            }
        }
        result.put("checked",checked);
        result.put("unChecked",unChecked);
        return CommonResponse.ok(result);
    }

    @Override
    public CommonResponse permissionList() {

        List<SysPermission> allPermissionList = this.list();


        return CommonResponse.ok(allPermissionList);
    }

    @Override
    public SysPermission getPermissionByCode(String oldRegionCode) {

        QueryWrapper<SysPermission> wrapper = new QueryWrapper<SysPermission>().eq("permission_code", oldRegionCode);
        SysPermission permission = this.getOne(wrapper);


        return permission;
    }
}
